package com.bw.login.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.common.utils.Md5UtilOriginal;
import com.bw.login.conf.JwtUtil;
import com.bw.login.conf.OssUtils;
import com.mysql.fabric.Response;
import com.netflix.client.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.bw.login.entity.UserEntity;
import com.bw.login.service.UserService;
import com.bw.common.utils.PageUtils;
import com.bw.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * 
 *
 * @author zhucaiyi
 * @email zhucaiyi@gmail.com
 * @date 2022-02-22 11:14:18
 */
@RestController
@RequestMapping("login/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		UserEntity user = userService.getById(id);

        return R.ok().put("user", user);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody UserEntity user){
		userService.save(user);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody UserEntity user){
		userService.updateById(user);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		userService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    @Autowired
    private JwtUtil jwtUtil;

    private static ThreadLocal<UserEntity> threadLocal= new ThreadLocal<>();

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("logout")
    public R logout(){

        String userkey = stringRedisTemplate.opsForValue().get("userkey");
        String[] split = userkey.split(",");
        UserEntity byId = userService.getById(split[0]);
        byId.setLastLoginData(new Date());
        userService.updateById(byId);
        stringRedisTemplate.delete("userkey");
        return R.ok();
    }
    @RequestMapping("/login")
    public R login(@RequestBody UserEntity userEntity, HttpSession session, HttpServletRequest request,HttpServletResponse response){
        QueryWrapper<UserEntity> nickname = new QueryWrapper<UserEntity>().eq("nickname", userEntity.getNickname());
        UserEntity byId = userService.getOne(nickname);
        if (byId!=null){
            String s = Md5UtilOriginal.md5(userEntity.getPassword());
            if (Md5UtilOriginal.md5(s).equals(byId.getPassword())){
//                session.setAttribute("user","1");
//                Cookie userkey = new Cookie("userkey", byId.getId()+"");
//                userkey.setMaxAge(24*60*60);                    // 设置过期时间1天，以秒为单位
//                response.addCookie(userkey);// 保存cookie到客户端
                stringRedisTemplate.opsForValue().set("userkey",byId.getId()+","+byId.getNickname());
                String token = jwtUtil.createJWT(byId.getId()+"", byId.getNickname(), "user");
                byId.setLoginCount(byId.getLoginCount()+1);
                userService.updateById(byId);
                return R.ok().put("token",token).put("data","登录成功");
            }
        }
        return R.error("登录失败");
    }

    @RequestMapping("/index")
    @ResponseBody
    public String index(HttpServletResponse response){
        Cookie userkey = new Cookie("userkey", "1234");
        userkey.setMaxAge(24*60*60);
        response.addCookie(userkey);
        return "你好";
    }

    @RequestMapping("/regist")
    public R regist(@RequestBody UserEntity userEntity){

        String s = Md5UtilOriginal.md5(userEntity.getPassword());
        String s1 = Md5UtilOriginal.md5(s);
        userEntity.setPassword(s1);
        userEntity.setRegisterData(new Date());
        userEntity.setSalt("bawei");
        userEntity.setLastLoginData(new Date());
        userEntity.setLoginCount(0);
        userService.save(userEntity);
        return R.ok().put("data","注册成功");
    }

    @RequestMapping("gethead")
    public String gethead(@RequestParam String name){

        QueryWrapper<UserEntity> nickname = new QueryWrapper<UserEntity>().eq("nickname", name);
        UserEntity byId = userService.getOne(nickname);
        return byId.getHead();
    }

    @Autowired
    private OssUtils ossUtils;

    @RequestMapping("upload")
    public R upload(@RequestParam MultipartFile file){

        R r = ossUtils.uploadFile(file);
        return r;
    }
    public static void main(String[] args) {
        String admin = Md5UtilOriginal.md5("admin");
        System.out.println("密码加密"+admin);
    }

}
